package cn.kgc.vue.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Score;
import cn.kgc.vue.exceptions.ExamTimeException;
import cn.kgc.vue.mapper.ScoreMapper;
import cn.kgc.vue.service.ScoreService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author mengshun
 * @description 针对表【sys_score】的数据库操作Service实现
 * @createDate 2024-04-17 10:31:01
 */
@Service
@Transactional
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements ScoreService {


    @Override
    public ResponseResult scorePage(QueryCondition<Score> queryCondition) {

        Page<Score> scorePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        String clazz = queryCondition.getSearchParams().getClazz();
        Date examTime = queryCondition.getSearchParams().getExamTime();

        LambdaQueryWrapper<Score> lambda = new LambdaQueryWrapper<>();
        lambda.eq(StringUtils.isNotBlank(clazz), Score::getClazz, clazz)
                .eq(ObjectUtils.isNotNull(examTime), Score::getExamTime, examTime);

        baseMapper.selectPage(scorePage, lambda);

        return ResponseResult.success()
                .data("total", scorePage.getTotal())
                .data("tableData", scorePage.getRecords());
    }

    @Override
    public ResponseResult importScore(MultipartFile file) throws Exception {

        // 判定文件是否为空
        if (file.isEmpty()) {
            return ResponseResult.fail().message("文件不能为空");
        }

        // 设置导入参数
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);

        InputStream inputStream = file.getInputStream();

        List<Score> scores = ExcelImportUtil.importExcel(inputStream, Score.class, importParams);


        scores.forEach(score -> {
            String studentNo = score.getStudentNo();
            Date examTime = score.getExamTime();
            LambdaQueryWrapper<Score> lambda = new QueryWrapper<Score>().lambda();
            lambda.eq(Score::getExamTime, examTime)
                    .eq(Score::getStudentNo, studentNo);

            Score score1 = baseMapper.selectOne(lambda);
            if (ObjectUtils.isNotNull(score1)) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = simpleDateFormat.format(examTime);

                throw new ExamTimeException(studentNo + ":" + format + "数据重复");
            }
            baseMapper.insert(score);
        });

        return ResponseResult.success().message("批量添加成功");
    }

    @Override
    public void exportScore(HttpServletResponse response, Map<String, Object> exportParams) {

        // 获取导出参数  clazz,examTime
        String clazz = (String) exportParams.get("clazz");
        Object examTime = exportParams.get("examTime");

        LambdaQueryWrapper<Score> lambda = new QueryWrapper<Score>().lambda();
        lambda.eq(StringUtils.isNotBlank(clazz), Score::getClazz, clazz)
                .eq(ObjectUtils.isNotNull(examTime), Score::getExamTime, examTime);

        List<Score> scores = baseMapper.selectList(lambda);

        ExportParams exportParam = new ExportParams();
        exportParam.setTitle("学生成绩表");
        exportParam.setSheetName("学生成绩表1");

        Workbook workbook = ExcelExportUtil.exportExcel(exportParam, Score.class, scores);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public ResponseResult scoreDataVisual() {

        List<Score> scores = baseMapper.selectScoreDataVisual();
        return ResponseResult.success()
                .data("list", scores);
    }
}




